package com.huanmeiqi.demo.quartz.demo02;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author cq.Wang
 * @date 2018/6/13 17:09
 * @description
 */
@Service
public class QuartzJobManager {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    /**
     * 添加Job
     * 多次添加，参数一样的话，后一次是无法添加成功的，会抛出because one already exists with this identification异常，该异常不会影响已经在运行的定时任务
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     * @param jobClass
     * @param cronExpression
     * @return
     */
    public Date addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass, String cronExpression) {
        Scheduler scheduled = schedulerFactoryBean.getScheduler();
        //job定义： // 任务名，任务组，任务执行类
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
        //触发器构建
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName, triggerGroupName).withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();
        try {
            // 返回的是第一次执行该添加的任务的时间
            return scheduled.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除
     *
     * @param jobName
     * @return
     */
//    public boolean deleteJob(String jobName) {
//        JobKey jobKey = new JobKey(jobName);
//        Scheduler scheduler = schedulerFactoryBean.getScheduler();
//        try {
//            return scheduler.deleteJob(jobKey);
//        } catch (SchedulerException e) {
//            e.printStackTrace();
//            System.err.println(e.getMessage());
//            return false;
//        }
//    }
}
